package com.gdc.miaosha.exception;

import com.gdc.miaosha.result.CodeMsg;
import com.gdc.miaosha.result.Result;
import com.google.common.base.Throwables;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * Description: 全局异常处理器
 * @author: gdc
 * @date: 2022/4/4
 * @version 1.0
 */
@Slf4j
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {

    @ExceptionHandler(value=Exception.class)
    public Result<String> exceptionHandler(Exception e){
        log.error("统一异常处理器，处理异常信息为：{}", Throwables.getStackTraceAsString(e));
        if(e instanceof GlobalException) {              // 自定义全局异常
            GlobalException ex = (GlobalException)e;
            return Result.error(ex.getCodeMsg());
        }else if(e instanceof BindException) {          // 参数绑定异常，用于校验传参
            BindException ex = (BindException)e;
            List<ObjectError> errors = ex.getAllErrors();
            ObjectError error = errors.get(0);
            String msg = error.getDefaultMessage();
            return Result.error(CodeMsg.BIND_ERROR.getCode(), String.format(CodeMsg.BIND_ERROR.getMsg(), msg));
        }else {
            return Result.error(CodeMsg.SERVER_ERROR);
        }
    }
}
